package org.rslai.socket.testtool.config;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Properties;

public class ReadCsv {

	/**
	 * 从 CSV　文件中读入数据
	 * @param directory CSV　数据文件所在的目录
	 * @param fileName CSV　数据文件文件名
	 * @return 返回读入的数据
	 */
	public HashMap<String, HashMap<String, String>> getData(String directory, String fileName) {

		String conURL = "jdbc:relique:csv:" + directory;
		String sqlStr = "select * from " + fileName;
		//LinkedList result = new LinkedList();
		HashMap<String, HashMap<String, String>> result = new HashMap<String, HashMap<String, String>>();

        /*
         * 配置 CsvDriver 高级选项
         */
        Properties info = new java.util.Properties();
        //info.put("separator","|");              // separator is a bar
        //info.put("suppressHeaders","true");     // first line contains data
        //info.put("fileExtension",".txt");       // file extension is .txt
        info.put("charset","UTF-8");       // file encoding is "ISO-8859-2"			

        try{
			Class.forName("org.relique.jdbc.csv.CsvDriver");
			Connection con = DriverManager.getConnection( conURL, info );

			Statement st = con.createStatement();
			ResultSet rs = st.executeQuery( sqlStr );

			/*
			 * 得到表格列数
			 */
            ResultSetMetaData metaData = rs.getMetaData();
            int CellNum = metaData.getColumnCount();
            String header[] = new String[CellNum];
            for (int i=2; i<=CellNum; i++) {
            	header[i-2] = metaData.getColumnName(i);
            }

			while(rs.next()) {
				HashMap<String, String> row = new HashMap<String, String>();
				
				if (rs.getObject(1).equals("T")) {
					for (int i = 1; i < CellNum; i++) {
						String value = stringValueOf( rs.getObject(i+1) );

						row.put(header[i-1], value);
					}

					result.put(stringValueOf(rs.getObject(2)), row);
				}
			}

			rs.close();
			st.close();
			con.close();

		} catch(Exception err) {
			err.printStackTrace(System.out);
		}

		return result;
	}

	private String stringValueOf(Object cell) {
		if (null == cell) {
			return "";
		}
		return cell.toString();
	}
}
